import numpy as np
import random

def Goldstein(func,dfunc,alpha,direc,x,t,c):
    """
    Goldstein准则
    param:{
        func：函数
        dfunc：函数偏导数
        c：条件参数
        alpha：上一步步长
        direc：搜索方向
        x：当前点位置
        t：步长系数
    }
    return:newAlpha：下一步搜索步长
    """
    flag = True
    
    left = 0
    right = alpha
    value = func(x)
    gradient = dfunc(x)
    factor = np.dot(gradient,direc)
    
    newAlpha = alpha*random.uniform(0,1)
    
    

    while(flag):
        newValue = func(x+newAlpha*direc)
        
        if(newValue -value<= c*newAlpha*factor):
            if(newValue -value>=(1-c)*newAlpha*factor):
                flag = False
            else:
                left = newAlpha
                right = right
                if(right<alpha):
                    newAlpha = (left+right)/2
                else:
                    newAlpha = t*newAlpha
        else:
            left = left
            right = newAlpha
            newAlpha = (left+right)/2
        
    
    return newAlpha

if __name__ == "__main__":
    x0 = np.array([-10,-11])